package cn.ddiancan.xddcloud.ddccore.request;


import java.util.Set;
import java.util.stream.Collectors;

import lombok.Getter;
import lombok.Setter;
import org.springframework.util.StringUtils;

@Getter
@Setter
public class PageRequest<T> {

    private T entity;

    /**
     * 页数
     */
    private Integer pageNo;

    /**
     * 每页数量
     */
    private Integer pageSize;

    private OrderByInfo orderByInfo;

    @Getter
    @Setter
    public class OrderByInfo {

        private String orderByColumns;

        private String orderByType = "desc";

        public String getOrderByColumns() {
            if (StringUtils.hasText(orderByColumns)) {
                Set<String> properties = StringUtils.commaDelimitedListToSet(orderByColumns);
                String collect = properties.stream().map(this::camelToUnderline).collect(Collectors.joining(","));
                return collect + " " + orderByType;
            }
            return orderByColumns;
        }

        public String camelToUnderline(String param) {
            int len = param.length();
            StringBuilder sb = new StringBuilder(len);
            for (int i = 0; i < len; i++) {
                char c = param.charAt(i);
                if (Character.isUpperCase(c) && i > 0) {
                    sb.append("_");
                }
                sb.append(Character.toLowerCase(c));
            }
            return sb.toString();
        }
    }
}
